<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
 </head>
 <body>
  <script type="text/javascript">          //这里text/javascript写反了，会显示不出来内容
      window.onload = function(){          //调用
	      Game.exe();
	  };

      //初始化
      var Game = {                         //把所有东西都放进一个对象里面，所有东西在Game里面实现。然后在外面调用他们就可以，这就是单体单例模式。
          
		  //启动程序
		  exe : function(){
			    document.body.style.background = '#000';
			    var oDiv = document.createElement('div');
			    oDiv.id = "GameBox";
				oDiv.style.cssText = 'width:300px;height:500px;border:10px solid #fff;margin:50px auto;position:relative;font-family:"Microsoft yahei";text-align:center;';
			    document.body.appendChild( oDiv );
			    this.init();
          },
          
		  score : 0,
		  ifEnd : true,                    //定义了一个开关
		 
		  //界面设计
	      init : function(){
			  //框
			  var This = this;       //
			  Game.ifEnd = true;
			  Game.score = 0;
              oDiv = document.getElementById('GameBox');
			  oDiv.innerHTML = '';
              //框内内容
			  //标题
			  var oH = document.createElement('h1');
			      oH.innerHTML = '飞机大战';
			      oH.style.cssText = 'color:#fff;font-size:30px;font-weight:normal;margin-top:50px;color:#fff;';
			      oDiv.appendChild( oH );
			  //选项
			  for (var i=0;i<4;i++ )
			  {
                  var oP = document.createElement('p');
				      oP.index = i;        //把for里面的i存起来，相当于给他一个序号。  
				  var html='';
				      oP.style.cssText = 'width:150px;height:40px;background:#fff;margin:50px auto;cursor:pointer;color:#000;font-size:16px;text-align:center;line-height:40px;';

				  switch ( i )             //通过switch方便创建4给p标签和内容
                  {
			          case 0: 
                      html = '简单模式';
					  break;
					  case 1:
					  html = '普通模式';
					  break;
					  case 2:
					  html = '困难模式';
					  break;
					  case 3:
					  html = '超神模式';
					  break;
                  }
			      //鼠标移进出选项动画
				  oP.onmouseenter = function(){
					  this.style.background = '#cc0033';
					  this.style.color = '#fff';
				  };
				  oP.onmouseleave = function(){
					  this.style.background = '#FFF';
					  this.style.color = '#000';
				  }

				  //点击选项开始游戏
				  oP.onclick = function( e ){
					  e = e || window.event;
					  This.start( oP.index , oDiv , e );
				  }

				  oP.innerHTML = html;
				  oDiv.appendChild( oP );
			  }
		  },

		  //游戏开始
		  start : function( index , oGameBox , e ){
			  oGameBox.innerHTML = '';
			  var oS = document.createElement('span');
			  oS.innerHTML = this.score;
			  oS.style.cssText = 'position:absolute;left:20px;top:10px;color:#fff;';
			  oGameBox.appendChild( oS );
 			  this.plane( oGameBox , e ,index );
			  this.enemy( oGameBox ,oS ,index );
		  },

		  //点击选项鼠标在飞机中心且随鼠标移动
		  plane : function( oGameBox , e ){
              var x = e.pageX;             //获取到页面鼠标的位置，就是ev事件
			  var y = e.pageY;
              
			  var oPlane = new Image();    //新创建一个图片元素  
			      oPlane.src = 'img/1.png';
                  oPlane.width = 60;
				  oPlane.height = 36;      //要先在此处如此定义长和宽  
		          oPlane.id = 'plane';
				  lx = oGameBox.offsetLeft+parseInt(oGameBox.style.borderWidth)+oPlane.width/2;    //然后在这里减去  
				  ty = oGameBox.offsetTop+parseInt(oGameBox.style.borderWidth)+oPlane.height/2;

				  window.onresize = function(){      //窗口宽度改变时候，使内容不变
					  lx = oGameBox.offsetLeft+parseInt(oGameBox.style.borderWidth)+oPlane.width/2; 
				  };

			  var left = x - lx;      
			  var top = y - ty;	  
                  oPlane.style.cssText = 'display:block;position:absolute;top:'+ top +'px;left:'+ left +'px;';
		          oGameBox.appendChild( oPlane );
		       
			  //设置飞位置的最大值
			  var leftMin = -oPlane.width/2;                              
			  var leftMax = oGameBox.clientWidth - oPlane.width/2;
			  var topMin = 0;
			  var topMax = oGameBox.clientHeight - oPlane.height;
                  
			  document.onmousemove = function( e ){
				   if (  Game.ifEnd )
			 {
				  e = e || window.event;
                  var left = e.pageX- lx;
			      var top = e.pageY- ty;

                      //设置极值的方法
				      left = Math.min( left , leftMax);   // if(left>leftMax)left=leftMax;
					  left = Math.max( left , leftMin);   // if(left<leftMin)left=leftMin;
					  top = Math.min( top , topMax);      // if(top>topMax)top=topMax;
					  top = Math.max( top , topMin);      // if(top<topMin)top=topMin;

				  oPlane.style.left = left + 'px';
				  oPlane.style.top = top + 'px';
			 }
			  };
			 
			 this.bullet( oPlane , oGameBox );            //this调用
		  },
          //子弹
		  bullet : function( oPlane , oGameBox ,index ){
			  //通过选项设置子弹和敌军速度
			  var speed;
					switch ( index )
					{
						case 0:
							speed = 200;
							break;
						case 1:
							speed = 300;
							break;
						case 2:
							speed = 400;
							break;
						case 3:
							speed = 10;
							break;
					}
			  Game.ifEnd = true;
			  this.Bullettimer = setInterval( function(){
			  var oBullet = new Image();
			      oBullet.src = 'img/4.png';
			      oBullet.width = 4;
			      oBullet.height = 22;
				  oBullet.className = 'Bullet';
              var top = oPlane.offsetTop-oBullet.height;
			  var left = oPlane.offsetLeft+oPlane.width/2-oBullet.width/2;
			      oBullet.style.cssText = 'position:absolute;top:'+top+'px;left:'+left+'px;';
			      oGameBox.appendChild( oBullet );
                  oBullet.timer = setInterval( function(){
                  oBullet.style.top = oBullet.offsetTop-3+'px';	
				  if ( oBullet.offsetTop < 0 )
				  {
                      clearInterval( oBullet.timer );
					  oBullet.parentNode.removeChild( oBullet );
				  }
             } , 13 );
			 } , speed );
		  },
		  
		  //敌军生成与掉落与检测与子弹的碰撞
		  enemy : function( oGameBox ,oS ,index ){
			        //通过选项设置子弹和敌军速度
			  		var a , x;
					switch ( index )
					{
						case 0:
							a = 1;
							x = 500;
							break;
						case 1:
							a = 3;
							x = 300;
							break;
						case 2:
							a = 5;
							x = 200;
							break;
						case 3:
							a = 5;
							x = 100;
							break;
					}
			Game.ifEnd = true;
			this.enemytimer = setInterval( function(){
				var oEnemy = new Image();
				oEnemy.src = 'img/2.jpg';
				oEnemy.width = 23;
				oEnemy.height = 30;

			var lMin = -oEnemy.width/2;
			var lMax = oGameBox.clientWidth-oEnemy.width/2;
			// Math.random()方法作用是生成0到1间的任意数
			var left = Math.random()*( lMax - lMin ) + lMin;  
            oEnemy.style.cssText = 'position:absolute;top:0px;left:'+left+'px;';
            oGameBox.appendChild( oEnemy );

            var b = Math.random()*a+1;  //这个放在这里，设置每个敌军下落速度不同。如果放在下面这个定时器里面的话，则效果是所有的敌军的速度是一样是随机的某一个。
			//敌军下落
			oEnemy.timer = setInterval( function(){		
		        oEnemy.style.top = oEnemy.offsetTop+b+'px';           //敌军下落
				if ( oEnemy.offsetTop > oGameBox.clientHeight-oGameBox.offsetTop+parseInt(oGameBox.style.borderWidth)*2 )   //如果敌军下落到盒子边框时候，把他删掉
				{
                    clearInterval( oEnemy.timer );
					oEnemy.parentNode.removeChild( oEnemy );
				}
			} , 13 );

			//检测与子弹的碰撞
			//检测子弹和敌军相撞
		    var allBullet = Game.getClass('Bullet');
            oEnemy.pztimer = setInterval( function(){
                for ( var i=0;i<allBullet.length;i++ )
                {
				    if ( Game.crash( oEnemy , allBullet[i]  ))
				    {
						Game.score ++;
                        oS.innerHTML = Game.score;
                        oEnemy.src='img/5.png';
					    clearInterval(oEnemy.pztimer);
                        allBullet[i].parentNode.removeChild(allBullet[i]);
                       //假如子弹与敌军碰撞后在下面延时定时器发生事件的时间之前掉下到上面所说的清楚敌军的界限时，会报错，这时候就需要一个判断，敌军的父级是否还在，也就是判断敌军是否还在
					    setTimeout(function(){	
                            if ( oEnemy.parentNode )
                            {
                                oEnemy.parentNode.removeChild( oEnemy );
                            }
					    } ,100 );
				    }
               }
            } , 50 );

           // 飞机与敌军碰撞
			var oPlane = document.getElementById('plane');
			Game.ifEnd = true;
			oEnemy.pzplane = setInterval(function(){
            if ( !Game.ifEnd )
            {
				 clearInterval( oEnemy.pzplane )          // 游戏结束后，把不是碰撞的定时器也关掉   
            }


			if ( Game.crash( oEnemy, oPlane) )
			{   
				Game.ifEnd = false;                       //把游戏结束定义为false
			    clearInterval( oEnemy.pzplane )          //游戏结束时候把碰撞的定时器关掉
			    oEnemy.src = 'img/5.png';
                oPlane.src = 'img/5.png';
                clearInterval( Game.Bullettimer );       //把子弹发射停止
				clearInterval( Game.enemytimer );        //把敌军下落停止
				setTimeout(function(){
					Game.over( GameBox );
				}, 1000 );

			}
			}, 100);

			} , x );
		  },
          
		  // 游戏结束
		  over : function ( oGameBox ){
            oGameBox.innerHTML = '';
			var Gameover = document.createElement('div');
			Gameover.style.cssText = 'width:200px;height:400px;margin:50px auto;background:#fff;';
			var H2 = document.createElement('h2');
			H2.innerHTML='GameOver';
			var oP1 = document.createElement('p');
            oP1.innerHTML = '你的得分是'+'<span style="color:red;font-weight:bold;">'+this.score+'</span>';
            oP1.style.cssText = 'font-size:18px;color:#000;';
			var oRestart = document.createElement('div');
			oRestart.style.cssText = 'width:100px;height:40px;color:red;background:#000;text-align:center;line-height:40px;margin:20px auto;cursor:pointer;';
			oRestart.innerHTML = '重新开始';
			oGameBox.appendChild( Gameover );
			Gameover.appendChild( H2 );
			H2.style.cssText = 'padding-top:50px;';
			Gameover.appendChild( oP1 );
            Gameover.appendChild( oRestart );

			oRestart.onclick = function(){
			    Game.init();	
			};

		  },


		





	      //碰撞检测
          crash : function( obj1 , obj2 ){   
			  var L1 = obj1.offsetLeft;
			  var R1 = L1 + obj1.clientWidth;
			  var T1 = obj1.offsetTop;
			  var B1 = T1 + obj1.clientHeight;

			  var L2 = obj2.offsetLeft;
			  var R2 = L2 + obj2.clientWidth;
			  var T2 = obj2.offsetTop;
			  var B2 = T2 + obj2.clientHeight;

			  if ( L1 > R2 || R1 < L2 || T1 > B2 || B1 < T2)
			  {
				  return false;
			  }
			  else
			  {
				  return true;
			  }
          },  

		  //获取子弹的getClass方法
		  getClass : function( cName , parent ){
			  parent = parent || document;
              if ( document.getElementsByClassName)
              {
				  return parent.getElementsByClassName( cName );
              }
			  else
			  {
				  var all = parent.getElementsByTagName('*');
				  var arr = [];
                  for( var i=0;i<=all.length;i++ )
                  {
                      arrClass = all.className.split('');
				      for ( var j=0;j<=arrClass.length;j++ )
				      {
						  if ( arrClass[j]==cName )
						  {
					          arr.push( all[i] );
							  break;
						  }
				      }
                  }
				  return arr;
			  }
		  },


      };
  </script>
 </body>
</html>

